package org.example.adservice.controller;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.example.adservice.common.Result;
import org.example.adservice.config.MinioConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * MinIO连接测试控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/test")
public class MinioTestController {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 测试MinIO连接
     */
    @GetMapping("/minio")
    public Result<String> testMinioConnection() {
        try {
            log.info("测试MinIO连接 - endpoint: {}, accessKey: {}", 
                    minioConfig.getEndpoint(), minioConfig.getAccessKey());
            
            // 尝试列出存储桶
            var buckets = minioClient.listBuckets();
            log.info("MinIO连接成功，找到 {} 个存储桶", buckets.size());
            
            StringBuilder result = new StringBuilder();
            result.append("MinIO连接成功！\n");
            result.append("Endpoint: ").append(minioConfig.getEndpoint()).append("\n");
            result.append("Access Key: ").append(minioConfig.getAccessKey()).append("\n");
            result.append("Bucket Name: ").append(minioConfig.getBucketName()).append("\n");
            result.append("存储桶数量: ").append(buckets.size()).append("\n");
            
            for (var bucket : buckets) {
                result.append("- ").append(bucket.name()).append(" (创建时间: ").append(bucket.creationDate()).append(")\n");
            }
            
            return Result.success(result.toString());
        } catch (Exception e) {
            log.error("MinIO连接测试失败", e);
            return Result.error("MinIO连接失败: " + e.getMessage());
        }
    }
}